﻿using SuperiorCommon;
using SuperiorModel;
using System;
using System.Drawing;
using System.IO;
using System.Web;
using System.Web.Mvc;

namespace SuperiorShopkeeper.Controllers
{
    [JsonException]
    [CheckLoginFitler]
    public class UploadController : BaseController
    {
        // GET: Upload
        public ActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// 公共上传图片
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult UploadImg()
        {
            try
            {
                HttpPostedFile file = System.Web.HttpContext.Current.Request.Files.Get(0);
                
                //验证上传的文件
                var uploadType = Request.QueryString["object"];
                var fileUploader =UploadService.GetUploadInstance(uploadType);
                string reason;
                if (!fileUploader.Validate(file.FileName, file.InputStream, out reason))
                {
                    var model = new LayuiUploadModel("-1", reason,null);
                    return Json(model);
                }

                //保存文件到指定文件夹  
                var newRandomCode = new Random().Next(1000);
                var fileName = string.Format("{0}_{1}{2}", DateTime.Now.ToString("yyyyMMddhhmmss"), newRandomCode, Path.GetExtension(file.FileName));
                var fullFileName = "";
                fullFileName = Path.Combine(fileUploader.TempPhysicalPath, fileName);
                file.SaveAs(fullFileName);
                //将文件路径作为返回值返回 
                var uploadFileName = "";
                uploadFileName = ConfigSettings.Instance.ImageHost + fileUploader.TempRelativePath + "/" + fileName;
                var result = new LayuiUploadModel("0", string.Empty, new LayuiUploadImgItem() { src = uploadFileName.ToForwardSlashPath(), title = "" });
                //判断图片超过100K，进行压缩
                if (file.ContentLength > 1024 * 100)
                {
                    var ret = true;
                    var fileName_cp = string.Format("{0}_{1}_cp{2}", DateTime.Now.ToString("yyyyMMddhhmmss"), new Random().Next(1000), Path.GetExtension(file.FileName));
                    using (Image image = Image.FromStream(file.InputStream))
                    {
                        var fullFileName_cp = Path.Combine(fileUploader.TempPhysicalPath, fileName_cp);
                        ret = ImgTool.Compress(fullFileName, fullFileName_cp, image.Height, image.Width, 50);

                    }
                    if (!ret)
                    {
                        LogManger.Instance.WriteLog("图片压缩失败,压缩文件：" + fullFileName);
                    }
                    else
                    {
                        //压缩成功删除临时目录压缩前的图片。
                        try
                        {
                            //将压缩后的新图片，返回给前端
                            var uploadFileName_cp = ConfigSettings.Instance.ImageHost + fileUploader.TempRelativePath + "/" + fileName_cp;
                            result.data.src = uploadFileName_cp.ToForwardSlashPath();
                            System.IO.File.Delete(fullFileName);
                        }
                        catch
                        {
                            LogManger.Instance.WriteLog("图片删除失败,文件：" + fullFileName);
                        }

                    }
                }

                return Json(result);
            }
            catch (Exception ex)
            {
                LogManger.Instance.WriteLog("上传图片异常：" + ex.ToString());
                return Json(new LayuiUploadModel("-1","图片上传异常",null));

            }
        }

       
    }
}